package com.zzj.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzj.bean.PlanBean;
import com.zzj.bean.ProductBean;
import com.zzj.bean.ShapeBean;
import com.zzj.dao.PlanDao;
import com.zzj.dao.ProductDao;
import com.zzj.dao.ShapeDao;
import com.zzj.utils.Result;
import com.zzj.utils.StatusCode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class PlanServiceImpl implements PlanService {
    @Resource
    private PlanDao planDao;
    @Resource
    private ProductDao productDao;
    @Resource
    private ShapeDao shapeDao;

    @Override
    public PageInfo<PlanBean> findByState(int pageNum,int pageSize,String state) {
        PageHelper.startPage(pageNum,pageSize);
        List<PlanBean> plans = planDao.findByState(state);
        return new PageInfo<>(plans);
    }

    @Override
    public Result updatePlan(PlanBean planBean) {
        // 数量
        int count = Integer.parseInt(planBean.getPamount());
        // 面积
        double area = Double.parseDouble(planBean.getParea());
        // 单价
        double price = planBean.getPprice();
        // 计算总金额
        planBean.setPmoney(count * area * price);
        planBean.setPstate("1");

        int i = planDao.updatePlan(planBean);

        List<ProductBean> products = productDao.findAllByOoidAndPtype(planBean.getOoid(), planBean.getPtype());
        // 每完成一个计划,就进入打型表
        for (int j = 0; j < count; j++) {
            ShapeBean shapeBean = new ShapeBean();
            shapeBean.setSstate("0");
            shapeBean.setPid(products.get(j).getPid());
            shapeDao.addShape(shapeBean);
        }

        if (i == 1){
            return new Result();
        }
        return new Result(false, StatusCode.ERROR,"操作失败");
    }

    @Override
    public Result<PlanBean> queryOneById(int pid) {
        PlanBean planBean = planDao.queryOneById(pid);
        if (planBean != null){
            return new Result<>(true,StatusCode.OK,"操作成功",planBean);
        }
        return new Result<>(false,StatusCode.ERROR,"操作失败");
    }

    @Override
    public PageInfo<PlanBean> findAll(int pageNum,int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<PlanBean> all = planDao.findAll();
        return new PageInfo<>(all);
    }
}
